from tornado.web import RequestHandler
import pymysql
import base64
import uuid
import os
from qiniu import Auth, put_file, etag, urlsafe_base64_encode
access_key = 'N_8YeN5vLOqLdZ7BDQ--JMXlg4AN_4X8GkWTVtOo'
secret_key = 'yZ4LlKY4PHjDvHi4l5-gFGn3iXDeDlR0o1Mwj6ca'
domin = 'http://p92yjj2v1.bkt.clouddn.com/'

def get_files(files):
    global access_key
    global secret_key
    res = dict(
		code = 0,
		message = '上传成功',
		data = []
	)
    count = 0
    fileslist = []
    while(files.get('file' + str(count))):
        fileslist.append(files['file' + str(count)][0])
        count += 1
    for file in fileslist:
        key = uuid.uuid1()
        filename = file.get('filename')
        upload_path = os.path.join(os.path.dirname(__file__), 'files')
        file_path = os.path.join(upload_path, filename)
        f = open(file_path, 'wb')
        f.write(file['body'])
        f.close()
        q = Auth(access_key, secret_key)
        bucket_name = 'xupeng-site'
        token = q.upload_token(bucket_name, key, 3600)
        ret, info = put_file(token, key, file_path)
        res['data'].append(ret['key'])
    return res

class BaseHandler(RequestHandler):
    def initialize(self):
        self.con = pymysql.connect(
            host = 'localhost',
            port = 3306,
            user = 'root',
            password = 'lf0429MR',
            db = 'pengjinyl',
            charset = 'utf8'
        )
        self.db = self.con.cursor(pymysql.cursors.DictCursor)
        self.openid = ''
        self.access_token = ''
    def query_sql(self, sql):
        self.db.execute(sql)
        return self.db.fetchall()

    def modify_sql(self, sql):
        try:
            self.db.execute(sql)
            self.con.commit()
            # self.db.close()
            return True
        except:
            return False
    def insert_sql(self, sql):
        try:
            self.db.execute(sql)
            self.con.commit()
            return True
        except:
            return False
    
    def res_success(self, type, data = [], object = {}):
        res = dict(
            code = 0,
            message = '',
            data = data,
            object = object
        )
        if type == 'query':
            res['message'] = '查询成功'
        elif type == 'insert':
            res['message'] = '新增成功'
        elif type == 'delete':
            res['message'] = '删除成功'
        elif type == 'modify':
            res['message'] = '修改成功'
        else:
            res['message'] = '不知道'
        return res
    def res_error(self, type):
        res = dict(
            code = 1
        )
        if type == 'query':
            res['message'] = '查询失败'
        elif type == 'insert':
            res['message'] = '新增失败'
        elif type == 'delete':
            res['message'] = '删除失败'
        elif type == 'modify':
            res['message'] = '修改失败'
        else:
            res['message'] = '不知道'
        return res

class SHandler(BaseHandler):
    def prepare(self):
        try:
            cookie = self.get_secure_cookie('sessionid')
            if bytes(self.query_sql('select adaccount from pj_config where id = 1')[0]['adaccount'], encoding = "utf8") == cookie:
                pass
            else:
                self.write(dict(
                    code = 2,
                    message = '未登录'
                ))
                self.finish()
        except:
            self.nologin = True
            self.write(dict(
                code = 2,
                message = '未登录'
            ))
# class UserHandler(BaseHandler):
#     def prepare(self):
#         try:
#             cookie = self.get_secure_cookie('sessionid')
#             if bytes(self.query_sql('select adaccount from pj_user where id = 1')[0]['adaccount'], encoding = "utf8") == cookie:
#                 pass
#             else:
#                 self.write(dict(
#                     code = 2,
#                     message = '未登录'
#                 ))
#                 self.finish()
#         except:
#             self.nologin = True
#             self.write(dict(
#                 code = 2,
#                 message = '未登录'
#             ))



